<?php
/**
 * User: @lose
 * Date: 2021/6/1
 * Time: 11:00 上午
 */

namespace Frieza\Modules\ContentCategory\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\ContentCategory\ContentCategoryMap as mContentCategoryMap;
use Doraemon\model\ContentCategory\ContentCategoryList as mContentCategoryList;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Encore\Admin\Layout\Content;
use Illuminate\Support\MessageBag;

class CategoryMapController
{
    public function index(Request $request, Content $content)
    {
        $request = $request->all();
        return $content
            ->header('前后台分类映射')
            ->breadcrumb(
                ['text' => '分类列表', 'url' => '/contentCategory/categoryMap']
            )
            ->body($this->listGird($request));
    }

    public function create(Content $content, $id = 0)
    {
        $categoryList = mContentCategoryList::getList();
        $option = [];
        foreach ($categoryList as $category) {
            $option[$category['id']] = $category['category'];
        }

        $data = [];
        if($id) {
            $data = mContentCategoryMap::get('*', ['id' => $id]);
        }
        $form = new Form($data);
        $form->hidden('id');
        $form->text('category_name', '分类名称')->required();
        $form->radio('module', '所属模块')->options(mContentCategoryMap::MODULE_MAP)->required();
        $form->select('category_id', '关联后台分类')->options($option)->required();
        $form->action('/admin/contentCategory/categoryMap/save');

        return $content
            ->header('分类管理')
            ->breadcrumb(
                ['text' => '前后台分类映射', 'url' => '/contentCategory/categoryMap'],
                ['text' => '添加分类', 'url' => '/contentCategory/categoryMap/create']
            )
            ->body($form);
    }

    public function save(Request $request)
    {
        try {
            $params = $request->all();
            if($params['id']) {
                // 编辑流程
                $data = [
                    'category_name' => $params['category_name'],
                    'module' => $params['module'],
                    'category_id' => $params['category_id'],
                    'edittime' => date('Y-m-d H:i:s'),
                    'admin_id' => Admin::user()->id,
                ];
                mContentCategoryMap::update($data, ['id' => $params['id']])->rowCount();
            } else {
                // 添加流程
                $data = [
                    'category_name' => $params['category_name'],
                    'module' => $params['module'],
                    'category_id' => $params['category_id'],
                    'addtime' => date('Y-m-d H:i:s'),
                    'admin_id' => Admin::user()->id,
                ];
                mContentCategoryMap::insert($data)->rowCount();
            }
            $success = new MessageBag([
                'title' => '提交成功'
            ]);
            return back()->with(compact('success'));
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '保存失败，请重试'
            ]);
            return back()->with(compact('error'))->withInput();
        }
    }

    public function delete($id = 0)
    {
        $result = mContentCategoryMap::update(['category_status' => mContentCategoryMap::STATUS_DELETE], ['id' => $id])->rowCount();
        if($result) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "删除失败",
            ]);
        }
    }

    public function listGird($request)
    {
        $where = $this->buildWhere($request);
        $infos = mContentCategoryMap::select('*', $where);
        $categoryList = mContentCategoryList::getList();
        $categoryList = array_column($categoryList, null, 'id');
        $gridModel = new pGridDataModel($infos, count($infos), []);

        return Admin::grid($gridModel, function (Grid $grid) use ($categoryList) {
            $grid->disableExport();
            $grid->disablePagination();
            $grid->disableRowSelector();
            $grid->filter(function (Grid\Filter $filter) {
                $filter->expand();
                $filter->disableIdFilter();
                $filter->equal('module', '所属模块')->select(mContentCategoryMap::MODULE_MAP);
            });

            $grid->column('id');
            $grid->column('category_name', '前台分类名称');
            $grid->column('module', '所属模块')->display(function () {
                return mContentCategoryMap::MODULE_MAP[$this->module];
            });
            $grid->column('category_id', '关联后台分类')->display(function () use($categoryList) {
                $category = $categoryList[$this->category_id];
                return "分类id:{$category['id']} <br> 分类名称:{$category['category']}";
            });
            $grid->column('addtime', '添加时间');
            $grid->column('admin_id', '最后操作者')->display(function () {
                return Admin::user()->find($this->admin_id)->name;
            });
        });
    }

    private function buildWhere($request)
    {
        $where = [];
        $where['category_status'] = mContentCategoryMap::STATUS_NORMAL;
        $where['ORDER'] = ['id' => 'DESC'];
        if(isset($request['module']) && $request['module']) {
            $where['module'] = $request['module'];
        }
        return $where;
    }
}